package crs.perfiles.dao;
// Generated 24-ene-2015 20:59:54 by Hibernate Tools 4.3.1

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import crs.users.model.Users;

import crs.perfiles.model.CrsPerfilCentro;

/**
 * Home object for domain model class CrsPerfilCentro.
 * @see .CrsPerfilCentro
 * @author Hibernate Tools
 */
@Repository
public class CrsPerfilCentroDaoImpl  implements CrsPerfilCentroDao {

	private static final Log log = LogFactory.getLog(CrsPerfilCentroDaoImpl.class);
	
	@Autowired
	private SessionFactory sf;
	
	public void persist(CrsPerfilCentro transientInstance) {
		log.debug("persisting CrsPerfilCentro instance");
		try {
			sf.getCurrentSession().persist(transientInstance);
			log.debug("persist successful");
		} catch (RuntimeException re) {
			log.error("persist failed", re);
			throw re;
		}
	}

	public void remove(CrsPerfilCentro persistentInstance) {
		log.debug("removing CrsPerfilCentro instance");
		try {
			sf.getCurrentSession().delete(persistentInstance);
			log.debug("remove successful");
		} catch (RuntimeException re) {
			log.error("remove failed", re);
			throw re;
		}
	}

	public CrsPerfilCentro merge(CrsPerfilCentro detachedInstance) {
		log.debug("merging CrsPerfilCentro instance");
		try {
			CrsPerfilCentro result = (CrsPerfilCentro) sf.getCurrentSession().merge(detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public CrsPerfilCentro findById(int id) {
		log.debug("getting CrsPerfilCentro instance with id: " + id);
		try {
			CrsPerfilCentro instance = (CrsPerfilCentro) sf.getCurrentSession().get(
					CrsPerfilCentro.class, id);
			log.debug("get successful");
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}
	
	/**
	 * Obtengo si el usuario tiene  un perfil de centro en cuyo caso devuelve 1
	 * @param username
	 * @return
	 */
	public long findByUserName(String username) {
		
		int count = 0;
        try {
        	count = ((Long)sf.getCurrentSession().createQuery("select count(*) from CrsPerfilCentro a join a.users b where a.centroid=b.userid and b.username=:username" )
            		.setParameter("username", username)
            		.uniqueResult()).intValue();
        } catch (Exception e) {
           throw new RuntimeException(); 
        }      
	        
	    return count ;
	}

	
}
